package com.stream.service.impl;

import com.stream.model.entity.UserEntity;
import com.stream.repository.UserRepository;
import com.stream.service.UserService;
import com.stream.utils.RRException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by yebaokang on 2017/5/26.
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    @SuppressWarnings("all")
    @Autowired
    private UserRepository userRepository;

    @Override
    public UserEntity queryObject(Long userId) {
        return userRepository.queryObject(userId);
    }

    @Override
    public List<UserEntity> queryList(Map<String, Object> map) {
        return userRepository.queryList(map);
    }

    @Override
    public int queryTotal(Map<String, Object> map) {
        return userRepository.queryTotal(map);
    }

    @Override
    public void save(String mobile, String password) {
        UserEntity user = new UserEntity();
        user.setMobile(mobile);
        user.setUserName(mobile);
        user.setPassword(DigestUtils.sha256Hex(password));
        user.setCreateTime(new Date());
        userRepository.save(user);
    }

    @Override
    public void update(UserEntity user) {
        userRepository.update(user);
    }

    @Override
    public void delete(Long userId) {
        userRepository.delete(userId);
    }

    @Override
    public void deleteBatch(Long[] userId) {
        userRepository.deleteBatch(userId);
    }

    @Override
    public UserEntity querryByMobile(String mobile) {
        return userRepository.queryByMobile(mobile);
    }

    @Override
    public long login(String mobile, String password) {
        UserEntity user = querryByMobile(mobile);

        Assert.isNull(user, "手机号或密码错误");

        if (!(StringUtils.equalsIgnoreCase(user.getPassword(), DigestUtils.sha256Hex(password)))) {
            throw new RRException("手机号或密码错误");
        }
        return  user.getUserId();
    }
}
